package com.centling.task;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.centling.business.SmsVO;
import com.centling.core.DBContextHolder;
import com.centling.service.ISmsService;
import com.centling.util.DateUtils;
import com.centling.util.SmsSender;

@Component
@Transactional
public class SmsSendTasks {

	private static Logger log = Logger.getLogger(SmsSendTasks.class);

	@Resource
	protected ISmsService smsService;

	@Value("${task.sms.send.daynum}")
	private Integer daynum;
	
	/**
	 * This task will be performed every 30 minutes
	 * @throws Exception 
	 */
	@Scheduled(cron = "0 0/${task.sms.send.mintus} * * * *")
	@Transactional
	private void smsCRM() throws Exception {
		String beginTime	= DateUtils.addDay(DateUtils.getCurrDate(), daynum)+" 00:00:00";
		String endTime		= DateUtils.getCurrDate()+" 23:59:59";
		log.info("Send SMS BeginTime:	"+beginTime);
		log.info("Send SMS EndTime :	"+endTime);
		DBContextHolder.setDBType(DBContextHolder.DATA_SOURCE_SMS);     
		List<SmsVO> list = smsService.getUnSendSms(beginTime, endTime);
		log.info("There are " + (list==null?0:list.size()) + " messages.");
		if (list!=null&&!list.isEmpty()){
			for (SmsVO vo : list){
				Integer returnVal = SmsSender.send(vo.getPhones(), vo.getContent());
				if (returnVal!=null){
					smsService.updateSmsByID(vo.getId(), 
							returnVal==0?"1":"0", 
							returnVal);
				}
			}
		}
		DBContextHolder.clearDBType();
	}
}
